package com.itfitness.optfragment;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import android.os.Bundle;
import android.util.Log;
import android.view.ViewGroup;

import com.google.android.material.tabs.TabLayout;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private ArrayList<Fragment> fragments = new ArrayList<>();
    private ArrayList<String> titles = new ArrayList<>();
    private ViewPager vp;
    private TabLayout tab;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        vp = (ViewPager) findViewById(R.id.vp);
        tab = (TabLayout) findViewById(R.id.tab);
        initDatas();
    }
    private void initDatas() {
        fragments.add(new TestFragment("页面1"));
        fragments.add(new TestFragment("页面2"));
        fragments.add(new TestFragment("页面3"));
        fragments.add(new TestFragment("页面4"));
        fragments.add(new TestFragment("页面5"));
        titles.add("页面1");
        titles.add("页面2");
        titles.add("页面3");
        titles.add("页面4");
        titles.add("页面5");
        vp.setAdapter(new MFragmentAdapter(getSupportFragmentManager(),fragments,titles));
        vp.setOffscreenPageLimit(fragments.size());
        tab.setupWithViewPager(vp);
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            Class<ViewPager> viewPagerClass = ViewPager.class;
            Field mItemsField = viewPagerClass.getDeclaredField("mItems");
            mItemsField.setAccessible(true);
            ArrayList mItems = (ArrayList) mItemsField.get(vp);
            Log.e("mItems",mItems.size() + "");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
